#include <my_header.h>

typedef struct share_state
{
    int flag;
    int ticketNum;
    pthread_mutex_t mLock;
}share_state_t;

void *purchaseFun(void *arg);
void *sellFun(void *arg);

/* usage */
int main(int argc, char *argv[])
{
    ARGS_CHECK(argc,1);

    /* 初始化 */
    share_state_t shareState;
    shareState.ticketNum = 20;
    shareState.flag = 0;//代表还没加票
    pthread_mutex_init(&shareState.mLock,NULL);

    /* 创建线程 */
    pthread_t pid1, pid2;
    pthread_create(&pid1,NULL,purchaseFun,&shareState);
    pthread_create(&pid2,NULL,sellFun,&shareState);

    /* 回收资源 */
    pthread_join(pid1,NULL);
    pthread_join(pid2,NULL);

    pthread_mutex_destroy(&shareState.mLock);

    return 0;
}

void *purchaseFun(void *arg)
{
    share_state_t *pshareState = (share_state_t *)arg;
    while(1)
    {
        pthread_mutex_lock(&pshareState->mLock);

        if(pshareState->ticketNum <=5 )
        {
            pshareState->ticketNum = pshareState->ticketNum +10;
            pshareState->flag = 1;
            pthread_mutex_unlock(&pshareState->mLock);
            break;
        }
        pthread_mutex_unlock(&pshareState->mLock);
    }
}


void *sellFun(void *arg)
{
    share_state_t *pshareState = (share_state_t *)arg;
    while(1)
    {
        pthread_mutex_lock(&pshareState->mLock);

        if(pshareState->ticketNum <=0 && pshareState->flag ==1)
        {
            pthread_mutex_unlock(&pshareState->mLock);
            break;
        }
        /* struct timeval nowTime; */
        /* gettimeofday(&nowTime,NULL); */
        /* srand((unsigned int)nowTime.tv_usec); */
        /* double rand_num = rand()/RAND_MAX; */
        srand(time(NULL));
        int rand_num = rand() %10 +1;

        if(pshareState->ticketNum >0 && rand_num<4)
        {
            pshareState->ticketNum--;
            printf("ticketNum = %d \n",pshareState->ticketNum);
        }
        pthread_mutex_unlock(&pshareState->mLock);
    }
}
